<template>
  <div class="tactics">
    <div class="topHandleCon">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-row :gutter="10" class="noBorderSelect">
            <el-col :span="11">
              <el-card :body-style="{padding:0}">
                <el-row>
                  <el-col :span="8">
                    <span class="spanBorder">状态</span>
                  </el-col>
                  <el-col :span="16">
                    <el-select
                      v-model="param.status"
                      size="mini"
                      clearable
                      @change="handleSearch"
                    >
                      <el-option
                        v-for="item of enabledmarkList"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                      />
                    </el-select>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
            <el-col :span="11">
              <el-card :body-style="{padding:0}">
                <el-row>
                  <el-col :span="8">
                    <span class="spanBorder">有效年度</span>
                  </el-col>
                  <el-col :span="16">
                    <el-select v-model="param.year" size="mini" clearable @change="handleSearch">
                      <el-option
                        v-for="item of controlType"
                        :key="item.encode"
                        :value="item.encode"
                        :label="item.name"
                        clearable
                      />
                    </el-select>
                  </el-col>
                </el-row>
              </el-card>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="14" class="greenBtnW">
          <el-row :gutter="10" :class="{'show-operate': !showOperate }">
            <el-col :span="14" class="txtR">
              <search
                v-model="search.value"
                :show-btn="false"
                placeholder="数据编码/名称"
                @btnClick="handleSearch"
              />
            </el-col>
            <el-col v-if="showOperate" :span="3" class="txtR">
              <div>
                <div
                  class="greenBtn"
                  @click="showAddData('add')"
                >新增</div>
              </div>
            </el-col>
            <el-col v-if="showOperate" :span="3" class="txtR">
              <div>
                <div class="greenBtn" @click="showAddData('edit')">修改</div>
              </div>
            </el-col>
            <el-col v-if="showOperate" :span="3" class="txtR">
              <div>
                <div class="greenBtn" @click="handleDeleteDictData">删除</div>
              </div>
            </el-col>

            <el-col :span="1" class="txtR">
              <div class="fresh">
                <div @click="handleInitData">
                  <i class="el-icon-refresh" />
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <div />
    <div class="tableCon paddingLeft" style="max-width: 1500px">
      <div class="leftList">
        <p>数据类型</p>
        <ul>
          <li
            v-for="type in module"
            :key="type.phid"
            :class="{ active: param.module === type.phid }"
            @click="handleClickType(type)"
          >{{ type.name }}</li>
        </ul>
      </div>
      <div class="tableShadow">
        <template v-if="tabsData.length">
          <el-tabs v-model="param.dictId" @tab-click="handleTabsClick">
            <el-tab-pane
              v-for="item in tabsData"
              :key="item.phid"
              :label="item.name"
              :name="item.phid + ''"
            />
          </el-tabs>
          <div v-if="param.dictId !== '2020031700000037'" style="width: 100%;height:calc(100% - 50px);position: relative">
            <el-table
              ref="multipleTable"
              :data="tableData"
              height="100%"
              tooltip-effect="dark"
              border
              @selection-change="handleSelectionChange"
            >
              <el-table-column width="80" header-align="center" align="center">
                <template slot="header" slot-scope="scope">
                  <el-checkbox
                    v-model="checkedAll"
                    :newname="scope.$index "
                    @change="checkedAllFn"
                  >序号</el-checkbox>
                </template>
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.checked" @change="rowChange">{{ scope.$index+1 }}</el-checkbox>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(item, index) in columnList"
                :key="index"
                :prop="item.prop"
                :label="item.label"
                :width="item.width || ''"
                header-align="center"
                align="center"
              >
                <!-- <template slot-scope="scope">
                  <template
                    v-if="scope.column.property == 'enabledmark'"
                  >{{ scope.row.enabledmark?'启用':'停用' }}</template>
                  <template
                    v-else-if="scope.column.property == 'ngInsertDt'"
                  >{{ scope.row.ngInsertDt.slice(0,4) }}</template>
                  <template v-else>{{ scope.row[scope.column.property] }}</template>
                </template> -->
              </el-table-column>
            </el-table>
          </div>
          <subject v-else/>
        </template>
        <template v-else>
          <div style="text-align:center;margin-top: 10%;">暂无数据</div>
        </template>
      </div>
      <div class="pageArea">
        <el-pagination
          :current-page="param.current"
          :page-sizes="[20,30,50,100,150,200]"
          :page-size="param.size"
          :total="param.total"
          layout="total,sizes,prev,pager,next,jumper"
          @size-change="handleSizeChange"
          @current-change="handleSearch"
        />
      </div>
    </div>
    <el-dialog
      v-if="addDataShow"
      :close-on-click-modal="false"
      :title="addDataType==='add'?'数据新增':'数据修改'"
      :visible.sync="addDataShow"
      custom-class="addUserCss"
      width="500px"
      append-to-body
    >
      <add-data-content :type="addDataType" :detail="addDataDetail" @close="finishAdd" />
    </el-dialog>
  </div>
</template>

  // { encode: 1, name: '操作员' }
  // { encode: 3, name: '平台管理员' }
  // { encode: 4, name: '组织单元管理员' }
  // { encode: 5, name: '组织管理员' }

<script>
import {
  getAllDictList,
  getDictDataList,
  deleteDictData
} from '@/api/dataCenter'
import search from '@/components/searchInput'
import { MODULE_LIST, DEFAULT_MODULE, VALID_DATE } from './constants'
import addDataContent from './addDataContent'
import { mapState } from 'vuex'
import Subject from './subject/index'
export default {
  name: 'UserManage',
  components: {
    search,
    addDataContent,
    Subject
  },
  provide() {
    return {
      getOrgList: this.getOrgList,
      getOrgTypeList: this.getOrgTypeList
    }
  },
  data() {
    return {
      module: MODULE_LIST,
      param: {
        module: DEFAULT_MODULE,
        dictId: '',
        current: 1,
        size: 10,
        status: '',
        year: '',
        name: '',
        total: 0
      },
      addDataType: '',
      addDataDetail: null,
      addDataShow: false,
      userRuleShow: false, // 角色授权弹窗
      addUserShow: false,
      addUserType: 'add',
      search: {},
      controlType: VALID_DATE,
      enabledmarkList: [{
        label: '启用',
        value: 0
      }, {
        label: '停用',
        value: 1
      }],
      tabsData: [], // tab数据
      tableData: [], // 表格数据
      checkedAll: false, // 全选
      columnList: [{
        prop: 'name',
        label: '名称'
      }, {
        prop: 'statusName',
        label: '状态'
      }, {
        prop: 'year',
        label: '有效年度'
      }, {
        prop: 'creator',
        label: '创建人'
      }, {
        prop: 'ngUpdateDt',
        label: '最后修改时间'
      }]
    }
  },
  computed: {
    ...mapState({
      orgId: state => state.user.orgId,
      userid: state => state.user.userid,
      usertype: state => state.user.usertype
    }),
    showOperate() {
      return [3, 2].includes(this.usertype)
    }
  },
  mounted() {
    this.handleInitData()
  },
  methods: {
    async handleInitData() {
      try {
        await this.getTabList()
        if (this.tabsData.length) {
          this.param.dictId = this.tabsData[0].phid + ''
          this.handleGetTableList()
        }
      } catch (err) {
        this.$msgBox.error('初始化数据错误')
      }
    },
    // 获取tab数据(策略列表)
    async getTabList() {
      try {
        const param = {
          module: this.param.module,
          orgId: this.orgId
        }
        const { data } = await getAllDictList(param)
        this.tabsData = data || []
      } catch (err) {
        this.$msgBox.error(err.msg)
        console.log(err, 'err')
      }
    },
    async handleGetTableList() {
      try {
        const { data: { total, records }} = await getDictDataList({ ...this.param })
        this.tableData = (records || []).map(v => ({
          ...v,
          statusName: ['启用', '停用'][v.status] || '',
          checked: false
        }))
        this.param.total = total
      } catch (err) {
        this.$msgBox.error('获取表格数据错误')
      }
    },
    handleClickType({ phid }) {
      this.param.module = phid
      this.handleInitData()
    },
    handleResetData() {
      this.checkedAll = false
      this.param = {
        module: DEFAULT_MODULE,
        dictId: '',
        current: 1,
        size: 10,
        status: '',
        year: '',
        name: '',
        total: 0
      }
    },
    handleGetCheckedData() {
      return this.tableData.filter(v => v.checked)
    },
    showAddData(type) {
      this.addDataType = type
      const checkedData = this.handleGetCheckedData()
      if (type === 'add') {
        console.log('add', checkedData)
        this.addDataDetail = {
          orgId: this.$store.state.user.orgId,
          parentId: checkedData.length ? checkedData[0].phid : 0,
          dictId: this.param.dictId,
          type: checkedData.length ? checkedData[0].type : 0
        }
      } else {
        if (!checkedData.length) {
          this.$msgBox.error('请选择要修改的用户!')
          return
        }
        if (checkedData.length > 1) {
          this.$msgBox.error('只能选择一个要修改的用户!')
          return
        }
        // FIXME: 解开注释
        // if (checkedData[0].creator != this.userid) {
        //   this.$msgBox.error('您无权操作此数据！')
        //   return
        // }
        this.addDataDetail = { ...checkedData[0] }
        console.log('edit', this.organizationInfo, checkedData)
      }
      this.addDataShow = true
    },
    handleSearch(param = {}) {
      this.param = {
        ...this.param,
        current: 1,
        ...param
      }
      this.handleGetTableList(this.param)
    },
    handleSizeChange(val) {
      this.handleSearch({ size: val })
    },
    handleCurrentChange(val) {
      this.handleSearch()
    },
    checkedAllFn(bool) {
      // 全选
      this.tableData = this.tableData.map(v => ({
        ...v,
        checked: bool
      }))
    },
    rowChange() {
      // 改变行
      this.checkedAll = this.tableData.every(table => {
        return table.checked
      })
    },
    // 删除
    handleDeleteDictData(data) {
      const checkedIds = this.handleGetCheckedData().map(v => v.phid)
      if (!checkedIds.length) {
        this.$msgBox.error('请先选择数据')
        return
      }
      this.$confirm('删除后不可恢复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deleteDictData({ ids: checkedIds })
      }).then((res) => {
        this.$msgBox.show('删除成功')
        this.handleGetTableList()
      }).catch(err => {
        console.log('err', err)
      })
    },
    finishAdd(bool) {
      // 完成或取消新增修改 ,true完成
      if (bool) {
        this.handleSearch({ current: 1 })
      }
      this.addDataShow = false
    },
    handleSelectionChange() {},
    handleTabsClick(tabInstance) {
      this.checkedAll = false
      this.param.current = 1
      this.param.dictId = tabInstance.name
      this.handleGetTableList(this.param)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
.tactics {
  min-width: 1250px;
  height: 100%;
  padding: 8px 0;
  overflow: hidden;
  position: relative;
}
.topHandleCon {
  padding: 0 20px;
  margin-top: 5px;
}
.noBorderSelect >>> .el-select {
  width: 100%;
  input {
    border: 0;
  }
}
.spanBorder {
  display: inline-block;
  width: 100%;
  height: 100%;
  line-height: 20px;
  margin-top: 4px;
  text-align: center;
  border-right: 1px solid $borderGray;
}
.greenBtnW {
  text-align: right;
  .greenBtn {
    margin: 0;
    min-width: 100%;
  }
  .fresh {
    height: 30px;
    line-height: 30px;
    font-size: 22px;
    text-align: center;
    cursor: pointer;
    color: #666;
  }
}
.tableCon {
  padding: 20px;
  padding-bottom: 70px;
  height: 100%;
  // position: relative;
  >>> .el-table--border {
    border: 0;
  }
  >>> .el-table::before {
    height: 0;
  }
  >>> .el-table::after {
    width: 0;
  }
  >>> .has-gutter tr > th:nth-last-of-type(2) {
    border-right: 0;
  }
}
.tableShadow {
  width: 100%;
  height: 100%;
  padding: 8px;
  box-shadow: 0 0 5px 3px #ddd;
  border-radius: 5px;
  overflow: hidden;
}
.paddingLeft {
  padding-left: 290px;
  .leftList {
    width: 250px;
    float: left;
    margin-left: -270px;
    height: 100%;
    box-shadow: 0 0 5px 3px #ddd;
    border-radius: 5px;
    text-align: center;
    overflow: hidden;
    > p {
      background: $green;
      height: 40px;
      line-height: 40px;
      color: #fff;
    }
    ul {
      > li {
        color: $btn_blue;
        height: 30px;
        line-height: 30px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;
        &:hover {
          background: #98c9f580;
        }
        &.active {
          cursor: default;
          background: #98c9f580;
        }
      }
    }
  }
}
.pageArea {
  position: absolute;
  right: 90px;
  bottom: 5px;
}
.show-operate {
  display: flex;
  justify-content: flex-end;
  margin-right: 10px;
}
</style>
<style lang="scss">
@import '@/styles/variables.scss';
.addUserCss {
  .el-dialog__header {
    background: $green;
    .el-dialog__title {
      color: #fff;
    }
  }
  border-radius: 10px;
  overflow: hidden;
}
</style>
